package cn.itcast.service.system.impl;

import cn.itcast.dao.system.ModuleDao;
import cn.itcast.dao.system.UserDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ModuleDao moduleDao;

    @Override
    public List<User> findAll(String companyId) {
        return userDao.findAll(companyId);
    }

    @Override
    public void insert(User user) {
        String password = user.getPassword();
        password = new Md5Hash(password, user.getEmail(), 2).toString();
        user.setPassword(password);
        userDao.insert(user);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public PageInfo findPage(String companyId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userDao.findAll(companyId);
        return new PageInfo(list, 5);
    }

    @Override
    public List<String> findRoleIdsByUserId(String userid) {
        return userDao.findRoleIdsByUserId(userid);
    }

    @Override
    @Transactional
    public void changeRole(String userid, String[] roleIds) {
        userDao.deleteRoleAndUserByUserId(userid);
        for (String roleId : roleIds) {
            userDao.saveUserAndRole(userid, roleId);
        }
    }

    @Override
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }

    @Override
    public List<Module> findModuleListByUser(User user) {
        Integer degree = user.getDegree();
        List<Module> list = null;
        if (degree == 0) {
            list = moduleDao.findByBelong(0);
        } else if (degree == 1) {
            list = moduleDao.findModuleListByCompanyId(user.getCompanyId());
        } else {
            list = moduleDao.findByUserId(user.getId());
        }
        return list;
    }

    public static void main(String[] args) {
        System.out.println(new Md5Hash("123456", "admin@export.com", 2).toString());
    }
}
